package com.lagou.edu.service.impl;

import com.lagou.edu.entity.LagouAuthCode;
import com.lagou.edu.entity.LagouToken;
import com.lagou.edu.entity.LagouUser;
import com.lagou.edu.mapper.LagouAuthCodeMapper;
import com.lagou.edu.mapper.LagouTokenMapper;
import com.lagou.edu.mapper.LagouUserMapper;
import com.lagou.edu.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

@Service
public class UserServiceLmpl implements UserService {

    @Autowired
    private LagouAuthCodeMapper lagouAuthCodeMapper;

    @Autowired
    private LagouUserMapper lagouUserMapper;

    @Autowired
    private LagouTokenMapper lagouTokenMapper;

    @Override
    @Transactional
    public String register(String email, String password, String code, HttpServletResponse response) {
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        Integer result = 0;
        // 查询最新的code
        LagouAuthCode lagouAuthCode =lagouAuthCodeMapper.getLastCode();
        // 校验是否过期
        String expireTime = lagouAuthCode.getExpireTime();
        LocalDateTime time = LocalDateTime.now();
        LocalDateTime ldt = LocalDateTime.parse(expireTime,df);
        if(ldt.isBefore(time)) return "验证码已失效";

        // 校验code 是否符合
        if(code.equals(lagouAuthCode.getCode()) ){

            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            LagouToken build = LagouToken.builder().email(email).token(uuid).build();
            int insertCount = lagouTokenMapper.insertToken(build);

            if(insertCount <=0) return "token生成失败";

            Cookie token = new Cookie("token",uuid);
            response.addCookie(token);
            LagouUser build1 = LagouUser.builder().password(password).email(email).build();
            lagouUserMapper.insertUser(build1);

        }
        return "注册成功";
    }

    @Override
    public boolean isRegistered(String email) {
        LagouUser userByEmail = lagouUserMapper.getUserByEmail(email);
        if(userByEmail != null){
            return true;
        }
        return false;
    }

    @Override
    @Transactional
    public String login(String email, String password) {
        LagouUser userByEmail = lagouUserMapper.getUserByEmail(email);
        if (userByEmail != null) {
            String queryPassword = userByEmail.getPassword();
            if (password.equals(queryPassword)) return email;
        }
        return null;
    }

    @Override
    public String info(String token) {
        return lagouTokenMapper.queryByToken(token);
    }
}
